<template>
  <div class="addTransportPlan">
    <div class="bottom">
      <div style="padding: 20px">
        <p class="title">基础信息</p>
        <el-form
          ref="transportForm"
          :model="transportModel"
          :rules="transportRule"
          label-width="120px"
          class="transportForm"
          label-position="top"
          size="medium"
        >
          <el-row :gutter="50">
            <el-col :span="6">
              <el-form-item label="供应商:" prop="supplier">
                <el-select
                  v-model="transportModel.supplier"
                  style="width: 100%"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item, index) in supplierOptions"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="起点:" prop="startPoint">
                <div class="cascader-wrapper">
                  <el-cascader
                    v-model="transportModel.startPoint"
                    separator="-"
                    :options="startPointOptions"
                    style="width: 100%"
                    placeholder="请选择"
                    clearable
                  />
                  <span
                    v-if="Array.isArray(transportModel.startPoint) && transportModel.startPoint.length > 0"
                    class="custom-suffix"
                  >
                    核载 {{ selectedNuclearPayload }}吨
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="终点:" prop="endPoint">
                <el-cascader
                  v-model="transportModel.endPoint"
                  separator="-"
                  :options="endPointOptions"
                  style="width: 100%"
                  placeholder="请选择"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="进厂时间:" prop="arrivalTime">
                <el-date-picker
                  v-model="transportModel.arrivalTime"
                  style="width: 100%"
                  type="datetimerange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="船名:" prop="teansportValue">
                <el-input v-model.trim="transportModel.teansportValue" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车型:" prop="vehicleType">
                <el-select v-model="transportModel.vehicleType" style="width: 100%" placeholder="请选择" multiple>
                  <el-option
                    v-for="(item, index) in vehicleTypeOptions"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单车趟次(趟):" prop="tripCount">
                <el-input v-model.trim="transportModel.tripCount" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求车数(辆):" prop="requiredCars">
                <el-input v-model.trim="transportModel.requiredCars" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购单号:" prop="采购单号">
                <el-select v-model="transportModel.采购单号" style="width: 100%" placeholder="请选择" multiple>
                  <el-option
                    v-for="(item, index) in systemOptions"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <p class="title">物料信息</p>
        <el-button type="primary" style="margin-bottom: 20px" @click="selectMaterial">+ 选择物料</el-button>
        <el-table
          ref="tablePage"
          :show-summary="true"
          :summary-method="getSummaries"
          :data="selectedMaterialTableData"
          style="width: 100%"
          :border="false"
          :header-cell-style="{ 'background-color': '#fafafa' }"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="materialType" label="物料类型" />
          <el-table-column prop="materialCode" label="物料编码" />
          <el-table-column prop="materialDescription" label="物料描述" />
          <el-table-column prop="unit" label="单位" />

          <!-- 自定义计划量(吨)列 -->
          <el-table-column label="计划量(吨)">
            <template v-slot="scope">
              <el-input v-model="plannedQuantity" placeholder="请输入计划量" size="medium" style="width: 50%" />
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="120" fixed="right">
            <template v-slot="scope">
              <el-button type="text" style="color: #ee3333" @click="handleDelete(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <LPTablePage
          ref="tablePage"
          :show-index="true"
          :show-summary="true"
          :table-data="selectedMaterialTableData"
          :table-column="selectedMaterialTableColumn"
          :total="total"
          :show-page="false"
          :current-page="currentPage"
          :selection="false"
          :selectable="selectable"
        >
          <template slot="plannedQuantity" slot-scope="{ row }">
            <el-input v-model="plannedQuantity" style="width: 50%" size="medium" placeholder="请输入计划量" />
          </template>
        </LPTablePage> -->
        <p class="title">分配预览</p>
        <el-table
          ref="tablePage"
          :show-summary="true"
          :summary-method="getNewSummaries"
          :data="previewTableData"
          style="width: 100%"
          :border="false"
          :header-cell-style="{ 'background-color': '#fafafa' }"
          @selection-change="handlePreviewSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="companyName" label="物流公司" />
          <el-table-column prop="plannedQuantity" label="计划量(吨)" />
          <el-table-column prop="requiredCars" label="需求车数(辆)" />
          <el-table-column prop="totalTrips" label="总趟次(趟)" />
          <el-table-column prop="tripsPerCar" label="单车趟次(辆)" />
          <el-table-column prop="dispatchPlan" label="派车方案" />
        </el-table>
        <div class="btn">
          <el-button class="button" @click="dialogVisible = false">取消</el-button>
          <el-button class="button" type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </div>
      <!-- 选择物料 -->
      <base-dialog
        :visible="addVisile"
        title="选择物料"
        width="1040px"
        style="margin-top: 0; margin-left: -20px; padding-top: 0.2rem"
        class="addDictDialog"
        @handleDialogSubmit="handleAddSubmit"
        @handleDialogCancle="handleAddCancle"
      >
        <el-form
          ref="addParams"
          :model="addParams"
          label-width="120px"
          class="dictForm"
          label-position="top"
          size="medium"
        >
          <search-bar
            v-model="searchModel"
            style="margin-bottom: 15px"
            :search-data="searchData"
            :config="searchData"
            @search="handleSearchSubmit"
            @searchReset="handleSearchReset"
          />
          <LPTablePage
            ref="tablePage"
            :show-index="true"
            :table-data="materialTableData"
            :table-column="materialTableColumn"
            :total="total"
            :current-page="currentPage"
            :selection="false"
            :highlight-current-row="true"
            @handleActiveCurrent="handleCurrentChange"
          />
        </el-form>
      </base-dialog>
    </div>
  </div>
</template>

<script>
import LPTablePage from '@/components/LPTablePage'
import SearchBar from '@/components/SearchBar'
import baseDialog from '@/components/BaseDialog'
import { addDateRange } from '@/utils/ruoyi'
import beiGangApi from '@/api/logistics/beigang'
export default {
  name: 'AddTransportPlan',
  components: {
    LPTablePage,
    SearchBar,
    baseDialog
  },
  data() {
    return {
      initialLoad: true,
      systemOptions: [],
      startPointOptions: [],
      selectedNuclearPayload: null,
      endPointOptions: [],
      vehicleTypeOptions: [],
      addVisile: false,
      addParams: {},
      searchModel: {},
      searchData: [
        {
          prop: 'materialType',
          type: 'select',
          placeholder: '物料类型',
          options: [
            { label: '原辅燃料', value: 'BX01' },
            { label: '成品及中间产品', value: 'BX02' },
            { label: '设备及专用备件', value: 'BX03' },
            { label: '通用备件', value: 'BX04' },
            { label: '辅助材料', value: 'BX05' },
            { label: '废旧物资', value: 'BX06' },
            { label: '能源动力', value: 'BX07' },
            { label: '服务类', value: 'BX08' },
            { label: '纺织类', value: 'BX09' }
          ]
        },
        { placeholder: '物料编码', prop: 'materialCode' },
        { placeholder: '物料描述', prop: 'materialDescription' },
        {
          prop: 'search',
          type: 'button',
          policy: ['system.log.query']
        }
      ],
      total: 0,
      currentPage: 1,
      materialTableData: [],
      materialTableColumn: [
        { label: '物料类型', prop: 'materialType' },
        { label: '物料编码', prop: 'materialCode' },
        { label: '物料描述', prop: 'materialDescription' },
        { label: '单位', prop: 'unit' }
      ],
      plannedQuantity: '',
      selectedMaterialTableData: [
        {
          materialCode: '4012357',
          materialDescription: '改向滚筒|￠320*750',
          materialType: '通用备件',
          materialTypeCode: 'BX04',
          unit: 'PC'
        }
      ],
      selectedMaterialTableColumn: [
        { label: '物料类型', prop: 'materialType' },
        { label: '物料编码', prop: 'materialCode' },
        { label: '物料描述', prop: 'materialDescription' },
        { label: '单位', prop: 'unit' },
        { label: '计划量(吨)', prop: 'plannedQuantity', render: true },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'button',
          width: 190,
          buttons: [
            {
              label: '删除',
              type: 'text',
              color: '#ee3333',
              method: 'handleDelete'
            }
          ]
        }
      ],
      previewTableData: [],
      previewTableColumn: [
        { label: '物流公司', prop: 'companyName' },
        { label: '计划量(吨)', prop: 'planQuantity' },
        { label: '需求车数(辆)', prop: 'requiredTrucks' },
        { label: '总趟次(趟)', prop: 'totalTrips' },
        { label: '单车趟次(辆)', prop: 'bicycleTrips' },
        { label: '派车方案', prop: 'dispatchPlan' }
      ],
      transportModel: {
        systemType: '',
        startPoint: '',
        endPoint: '',
        arrivalTime: '',
        teansportValue: '',
        vehicleType: '',
        tripCount: 1,
        requiredCars: 0
      },
      transportRule: {
        systemType: [{ required: true, trigger: 'blur', message: '必填' }],
        startPoint: [{ required: true, trigger: 'blur', message: '必填' }],
        endPoint: [{ required: true, trigger: 'blur', message: '必填' }],
        arrivalTime: [{ required: true, trigger: 'blur', message: '必填' }],
        vehicleType: [{ required: true, trigger: 'blur', message: '必填' }],
        tripCount: [{ required: true, trigger: 'blur', message: '必填' }],
        requiredCars: [{ required: true, trigger: 'blur', message: '必填' }]
      },
      supplierOptions: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    // 监听数据变化，确保数据更新后依然保持全选
    // previewTableData(newVal) {
    //   this.$nextTick(() => {
    //     // 只在初始加载时勾选所有项
    //     if (newVal.length > 0 && !this.initialLoad) {
    //       this.$refs.tablePage.toggleAllSelection()
    //     }
    //     // 在每次更新后，重置初始加载标志
    //     this.initialLoad = false
    //   })
    // },
    // 监听基础信息中“单车趟次”的变化
    'transportModel.tripCount'(newVal) {
      // 更新分配预览表格中“单车趟次”列的值
      this.previewTableData = this.previewTableData.map((item) => ({
        ...item,
        tripsPerCar: newVal
      }))
    },
    // 监听计划量、核载量和单车趟次变化
    plannedQuantity: 'calculateRequiredCars',
    selectedNuclearPayload: 'calculateRequiredCars',
    'transportModel.tripCount': 'calculateRequiredCars',

    'transportModel.startPoint': function (newValue) {
      if (newValue.length === 2) {
        // 确保选择了二级选项
        const selectedParent = this.startPointOptions.find((option) => option.value === newValue[0])
        if (selectedParent) {
          const selectedChild = selectedParent.children.find((child) => child.value === newValue[1])
          this.selectedNuclearPayload = selectedChild ? selectedChild.nuclearPayload : null // 获取核载量
        } else {
          this.selectedNuclearPayload = null // 重置核载量
        }
      } else {
        this.selectedNuclearPayload = null // 如果没有选择，重置核载量
      }
    }
  },
  mounted() {
    this.getLogininforList()
    // 删除
    this.$bus.$on('handleDelete', (rows) => {
      this.$confirm('确定删除吗', '取消', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {})
    })
    this.previewTableData = []
    // 设置单车趟次列值为 1
    // this.previewTableData.forEach((item) => {
    //   item.tripsPerCar = 1 // 将每个对象的 tripsPerCar 属性设置为 1
    // })
  },
  methods: {
    calculateRequiredCars() {
      const plannedQuantity = parseFloat(this.plannedQuantity)
      const nuclearPayload = parseFloat(this.selectedNuclearPayload)
      const tripCount = parseFloat(this.transportModel.tripCount)

      if (isNaN(plannedQuantity) || isNaN(nuclearPayload) || nuclearPayload <= 0) {
        // 数据无效或核载量无效时不进行计算
        return
      }

      // 重置所有行的数据
      this.previewTableData.forEach((item) => {
        this.$set(item, 'totalTrips', '') // 重置总趟次
        this.$set(item, 'tripsPerCar', '') // 重置单车趟次
        this.$set(item, 'requiredCars', '') // 重置需求车数
        this.$set(item, 'plannedQuantity', '') // 重置需求车数
        this.$set(item, 'dispatchPlan', '') // 重置派车方案
      })

      // 获取选中的行
      const selectedRows = this.$refs.tablePage.selection || []
      const selectedRowCount = selectedRows.length

      if (selectedRowCount === 0) {
        this.transportModel.requiredCars = '' // 无选中行则不计算
        return
      }

      // 计算基础信息的总需求车数
      const totalRequiredCars = Math.ceil(plannedQuantity / nuclearPayload / tripCount)

      // 分配需求车数
      const baseCars = Math.floor(totalRequiredCars / selectedRowCount)
      let carRemainder = totalRequiredCars % selectedRowCount

      // 随机打乱选中的行顺序，以便公平分配余数
      selectedRows.sort(() => Math.random() - 0.5)

      selectedRows.forEach((row) => {
        // 分配需求车数给每一行，余数分配给前面的几行
        const rowRequiredCars = baseCars + (carRemainder > 0 ? 1 : 0)
        this.$set(row, 'requiredCars', rowRequiredCars)

        // 更新每行的 totalTrips = requiredCars * tripCount
        const totalTrips = rowRequiredCars * tripCount
        this.$set(row, 'totalTrips', totalTrips)

        // 设置单车趟次
        this.$set(row, 'tripsPerCar', tripCount)

        // 计算计划量 = totalTrips * 核载量
        const plannedQuantityForRow = totalTrips * nuclearPayload
        this.$set(row, 'plannedQuantity', plannedQuantityForRow)

        // 生成派车方案，格式为“X辆车，单车Y趟”
        const dispatchPlan = `${rowRequiredCars}辆车，单车${tripCount}趟`
        this.$set(row, 'dispatchPlan', dispatchPlan)

        carRemainder-- // 每分配一次余数，减少1
      })

      // 更新 transportModel 的总需求车数
      this.transportModel.requiredCars = totalRequiredCars
    },
    getSummaries({ columns, data }) {
      const plannedQuantity = this.plannedQuantity
      const sums = []
      columns.forEach((column, index) => {
        if (index === 5) {
          // 获取计划量(吨)的合计
          const totalQuantity = data.reduce((sum, row) => {
            // 确保 plannedQuantity 是数字
            const quantity = parseFloat(plannedQuantity) || 0
            return sum + quantity
          }, 0)
          sums[index] = `${totalQuantity.toFixed(3)} `
        } else if (index === 0) {
          sums[index] = '合计'
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    getNewSummaries({ columns, data }) {
      const sums = []

      columns.forEach((column, index) => {
        // 只显示合计的标题在第0列，其他列设置为空
        if (index === 0) {
          sums[index] = '合计' // 合计标题
        } else if (index === 1 || index === 2 || index === 6 || index === 7) {
          sums[index] = '' // 不显示第1列和第2列
        } else {
          // 对于其他列进行合计计算
          const total = data.reduce((sum, row) => {
            const value = parseFloat(row[column.property]) || 0 // 确保取到正确的值并进行数字转换
            return sum + value
          }, 0)
          sums[index] = total.toFixed(0) // 保留3位小数
        }
      })

      return sums
    },
    handleSearchSubmit() {
      this.currentPage = 1
      this.selectMaterial()
      // this.getLogininforList()
    },
    handleSearchReset() {
      this.currentPage = 1
      this.$refs.tablePage.clearSelection()
      this.selectMaterial()
    },
    handleSubmit() {
      this.$refs.transportForm.validate((valid) => {
        if (valid) {
          console.log('提交表单', this.transportModel)
        } else {
          console.log('验证失败')
          return false
        }
      })
    },
    handleCancel() {},
    // 选择物料
    handleAddSubmit() {
      if (this.selectedMaterialTableData.length == 0) {
        this.$message({
          message: '请选择物料后再操作',
          type: 'warning'
        })
      } else {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.addVisile = false
      }
    },
    handleAddCancle() {
      this.addVisile = false
      this.selectedMaterialTableData = []
    },
    handleCurrentChange(row) {
      if (row) {
        this.selectedMaterialTableData = [row]
      } else {
        console.warn('当前行数据为空')
      }
    },
    // 分配预览
    handlePreviewSizeChange() {},
    handlePreviewCurrentChange() {},
    handlePreviewSelectionChange(selectedRows) {
      // 调用计算方法更新表格中的数据
      this.calculateRequiredCars(selectedRows)
    },
    // 获取物料
    selectMaterial() {
      const { pageSize } = this.$refs.tablePage
      const params = {
        ...this.searchModel,
        pageSize: pageSize,
        pageNum: this.currentPage
      }
      this.addVisile = true
      beiGangApi.materialList(params).then((res) => {
        this.materialTableData = res.data
      })
    },
    selectable(row, index) {
      // if (row.status == 0) {
      //   return true
      // } else {
      //   return false
      // }
      return true
    },
    getLogininforList() {
      const { pageSize } = this.$refs.tablePage
      const params = {
        pageSize: pageSize,
        pageNum: this.currentPage
      }
      const obj = addDateRange(params, this.searchModel.loginTime)
      delete obj.loginTime
      // 获取供应商
      beiGangApi.supplierList().then((res) => {
        if (res.code == 200) {
          const supplier = res.data.map((supplier) => ({
            label: supplier.ksqc,
            value: supplier.srmgysbm
          }))
          this.total = res.data.length
          this.supplierOptions = supplier
        }
      })
      const paranms1 = {
        auditStatus: 1,
        isEnabled: 1,
        pageSize: pageSize,
        pageNum: this.currentPage
      }
      beiGangApi.logisticsCompanyoList(paranms1).then((res) => {
        if (res.code == 200) {
          // 获取成功，设置表格数据
          this.previewTableData = res.rows.map((item) => {
            return {
              ...item,
              tripsPerCar: 1 // 设置单车趟次为 1
            }
          })
          this.$nextTick(() => {
            this.$refs.tablePage.toggleAllSelection() // 选中所有行
          })
        }
      })
      // 获取起点
      beiGangApi.getByType({ useTo: '起点' }).then((res) => {
        if (res.code === 200) {
          // 将顶层属性名“仓库”作为一级选项，内部对象作为二级选项
          const startPointOptions = Object.keys(res.data).map((key) => ({
            label: key, // 一级选项标签，值为“仓库”等顶级属性名
            value: key,
            children: res.data[key].map((item) => ({
              label: item.name, // 二级选项标签，值为具体仓库/港口的名称
              value: item.locationId, // 二级选项值
              nuclearPayload: item.nuclearPayload,
              children: item.nestedData
                ? item.nestedData.map((nestedItem) => ({
                    label: nestedItem.name, // 三级选项标签
                    value: nestedItem.locationIdid, // 三级选项值
                    nuclearPayload: nestedItem.nuclearPayload
                  }))
                : null
            }))
          }))
          // 将选项赋值给对应的 searchData
          this.startPointOptions = startPointOptions
        }
      })
      // 获取终点
      beiGangApi.getByType({ useTo: '终点' }).then((res) => {
        if (res.code === 200) {
          // 构造终点选项结构，类似起点
          const endPointOptions = Object.keys(res.data).map((key) => ({
            label: key,
            value: key,
            children: res.data[key].map((item) => ({
              label: item.name,
              value: item.locationId,
              children: item.nestedData
                ? item.nestedData.map((nestedItem) => ({
                    label: nestedItem.name,
                    value: nestedItem.id
                  }))
                : null
            }))
          }))
          // 将选项赋值给对应的 searchData
          this.endPointOptions = endPointOptions
        }
      })
      beiGangApi
        .getVehicleModel('drivingVehicleType')
        .then((res) => {
          if (res.code === 200 && res.data && res.data.sysDictDataDetailList) {
            // 处理接口返回的数据，将dictValue作为label，id作为value
            this.vehicleTypeOptions = res.data.sysDictDataDetailList.map((item) => ({
              value: item.dictValue,
              id: item.id
            }))
          } else {
            console.error('数据获取失败或数据格式不正确')
          }
        })
        .catch((error) => {
          console.error('接口请求失败:', error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.cascader-wrapper {
  position: relative;
  width: 100%;
}

.custom-suffix {
  position: absolute;
  right: 10%; /* 距离右边距离 */
  top: 50%;
  transform: translateY(-50%);
  color: white;
  background-color: #dca550;
  height: 22px;
  line-height: 22px;
  padding: 0 3px;
  // border-radius: 4px;
  pointer-events: none; /* 确保不影响选择框点击 */
}
.addTransportPlan {
  .title {
    font-size: 18px;
    font-weight: 700;
  }
}
.btn {
  position: fixed;
  bottom: 20px;
  right: 40px;
  display: flex;
  justify-content: flex-end;
  z-index: 999;
  .button {
    margin-left: 10px;
    width: 80px;
  }
}
::v-deep .el-table thead {
  color: #666666;
}
::v-deep .el-table__footer-wrapper {
  height: 49px;
}
::v-deep .el-table-column--selection .cell {
  padding-left: 12px;
}
::v-deep .el-table__footer .has-gutter .cell {
  font-weight: 700;
}
::v-deep .el-table__footer .has-gutter:nth-child(2) .is-leaf:nth-child(4) .cell,
::v-deep .el-table__footer .has-gutter:nth-child(2) .is-leaf:nth-child(5) .cell,
::v-deep .el-table__footer .has-gutter:nth-child(2) .is-leaf:nth-child(6) .cell {
  color: #3274f6;
}
</style>
